package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.hmdp.common.utils.RedisConstants.QUERY_SHOP_KEY;
import static com.hmdp.common.utils.RedisConstants.QUERY_SHOP_TTL;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private com.hmdp.common.utils.CacheClient CacheClient;

    @Override
    public Result queryById(Long id) {

        Shop shop = CacheClient.queryWithPassThrough(QUERY_SHOP_KEY + id, Shop.class, () -> getById(id), QUERY_SHOP_TTL, TimeUnit.MINUTES);

//        Shop shop = CacheClient.queryWithLogicalExpire(
//                QUERY_SHOP_KEY + id, Shop.class, () -> getById(id), QUERY_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("您查询的店铺不存在！");
        }
        return Result.ok(shop);

    }

    @Transactional
    @Override
    public Result updateShop(Shop shop) {

//      为最大限度的保证数据一致性  先进行数据库数据更新，然后再删除缓存  并使用事务
        boolean flag = updateById(shop);
        if (flag) {
//           更新成功，删除缓存
            stringRedisTemplate.delete(QUERY_SHOP_KEY + shop.getId());
            return Result.ok();
        } else {
            return Result.fail("更新操作未成功执行。");
        }
    }
}
